import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Layout,
  Card,
  Table,
  Button,
  Space,
  Typography,
  Input,
  Select,
  Statistic,
  Row,
  Col,
  Progress,
  message,
  Modal,
  Radio,
} from 'antd';
import {
  FolderOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined,
  ReloadOutlined,
  TeamOutlined,
  SwapOutlined,
  EditOutlined,
  PlayCircleOutlined,
  UnorderedListOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import { directoryApi, teamApi } from '../services/api';
import TeamDistributionModal from '../components/TeamDistributionModal';

const { Title, Text } = Typography;
const { Option } = Select;
const { Content } = Layout;

interface DirectoryInfo {
  id?: number;  // directory_id (optional for backward compatibility)
  directory_path: string;
  file_path: string;
  metric_count: number;
  analyzed_count: number;
  not_analyzed_count: number;
  analysis_progress: number;
  file_name: string;
  team_id?: string;
  team_name?: string;
  assigned_teams?: string[];
  team_count?: number;
  assignment_confidence?: number;
  assignment_method?: string;
  assigned_at?: string;
}

const DirectoryList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [teamsLoading, setTeamsLoading] = useState(false);
  const [directories, setDirectories] = useState<DirectoryInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [totalMetrics, setTotalMetrics] = useState(0);
  const [teams, setTeams] = useState<Array<{
    id: string;
    name: string;
    description?: string;
  }>>([]);

  // 团队分布 ({record.team_count || 0})弹窗状态
  const [teamDistributionVisible, setTeamDistributionVisible] = useState(false);
  const [selectedDirectoryForTeam, setSelectedDirectoryForTeam] = useState<{id: number, path: string} | null>(null);

  // 分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });

  // 筛选参数
  const [filters, setFilters] = useState({
    search: '',
    teamFilter: 'all',
  });

  // 排序状态
  const [sortState, setSortState] = useState({
    field: 'metric_count',
    order: 'desc' as 'asc' | 'desc',
  });

  // 防止重复API调用的ref
  const isLoadingRef = useRef(false);
  const totalMetricsLoadingRef = useRef(false);
  const teamsLoadingRef = useRef(false);

  // 批量操作相关状态
  const [batchModalVisible, setBatchModalVisible] = useState(false);
  const [batchModalType, setBatchModalType] = useState<'team' | 'analysis'>('team');
  const [selectedDirectory, setSelectedDirectory] = useState<DirectoryInfo | null>(null);
  const [selectedTeam, setSelectedTeam] = useState<string>('');
  const [teamAnalysisNotes, setTeamAnalysisNotes] = useState<string>('');
  const [batchOperationLoading, setBatchOperationLoading] = useState(false);

  // 批量分析相关状态
  const [analysisShouldCollect, setAnalysisShouldCollect] = useState<boolean | null>(null);
  const [analysisReason, setAnalysisReason] = useState<string>('');

  // 加载总遥测点数量
  const loadTotalMetrics = useCallback(async () => {
    if (totalMetricsLoadingRef.current) {
      console.log('📋 [DirectoryList] Total metrics API已在加载中，跳过重复请求');
      return;
    }

    try {
      totalMetricsLoadingRef.current = true;
      const response = await fetch('/api/v1/stats/overview');
      const data = await response.json();
      if (data.success && data.data?.total_metrics) {
        setTotalMetrics(data.data.total_metrics);
      }
    } catch (error) {
      console.error('❌ [DirectoryList] Failed to load total metrics:', error);
    } finally {
      totalMetricsLoadingRef.current = false;
    }
  }, []);

  // 加载团队列表
  const loadTeams = useCallback(async () => {
    if (teamsLoadingRef.current) {
      console.log('📋 [DirectoryList] Teams API已在加载中，跳过重复请求');
      return;
    }

    try {
      teamsLoadingRef.current = true;
      setTeamsLoading(true);
      console.log('🏢 [DirectoryList] Loading teams list');

      const response = await teamApi.getTeams();

      if (Array.isArray(response)) {
        console.log(`🏢 [DirectoryList] Loaded ${response.length} teams`);
        setTeams(response);
      }
    } catch (error: any) {
      console.error('❌ [DirectoryList] Failed to load teams:', error);
      message.error('加载团队列表失败');
    } finally {
      teamsLoadingRef.current = false;
      setTeamsLoading(false);
    }
  }, []);

  // 加载目录列表
  const loadDirectoryList = useCallback(async () => {
    if (isLoadingRef.current) {
      console.log('📋 [DirectoryList] Directory list API已在加载中，跳过重复请求');
      return;
    }

    try {
      isLoadingRef.current = true;
      setLoading(true);
      console.log(`📁 [DirectoryList] Loading directory list`);

      // 确保团队过滤器使用团队名称而不是团队ID
      const teamFilterValue = filters.teamFilter === 'all'
        ? undefined
        : getTeamNameFromId(filters.teamFilter);

      const response = await directoryApi.getDirectoryList({
        page: pagination.current,
        page_size: pagination.pageSize,
        search: filters.search || undefined,
        sort_by: sortState.field,
        sort_order: sortState.order.toUpperCase(),
        team_filter: teamFilterValue,
      });

      if (response && response.success) {
        console.log(`📁 [DirectoryList] Loaded ${response.data?.length || 0} directories`);
        // Transform the new API response structure to match the existing component
        const transformedData = (response.data || []).map((item: any) => ({
          id: item.id, // Add missing id field for team distribution button
          directory_path: item.path,
          file_path: item.path,
          metric_count: item.metric_count,
          analyzed_count: item.analyzed_count || 0, // Use API provided value
          not_analyzed_count: item.not_analyzed_count || 0, // Use API provided value
          analysis_progress: item.analysis_progress || 0, // Use API provided value
          file_name: item.name,
          team_id: item.team_id,
          team_name: item.team_name,
          assigned_teams: item.assigned_teams || (item.team_name ? [item.team_name] : []),
          team_count: item.team_count || (item.team_name ? 1 : 0),
          assignment_confidence: item.assignment_confidence,
          assignment_method: item.assignment_method,
          assigned_at: item.assigned_at,
        }));
        setDirectories(transformedData);
        setTotal(response.total_count || 0);
      }
    } catch (error: any) {
      console.error('❌ [DirectoryList] Failed to load directory list:', error);
      message.error('加载目录列表失败');
      setDirectories([]);
      setTotal(0);
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
    }
  }, [pagination.current, pagination.pageSize, filters.search, filters.teamFilter, sortState.field, sortState.order]);

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination({ current: page, pageSize });
  };

  // 键盘翻页处理函数
  const handleKeyboardPagination = useCallback((direction: 'prev' | 'next') => {
    const totalPages = Math.ceil(total / pagination.pageSize);

    if (direction === 'prev' && pagination.current > 1) {
      setPagination(prev => ({ ...prev, current: prev.current - 1 }));
    } else if (direction === 'next' && pagination.current < totalPages) {
      setPagination(prev => ({ ...prev, current: prev.current + 1 }));
    }
  }, [pagination.current, pagination.pageSize, total]);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // 如果焦点在输入框中，不处理键盘事件
      const activeElement = document.activeElement;
      if (activeElement && (
        activeElement.tagName === 'INPUT' ||
        activeElement.tagName === 'TEXTAREA' ||
        activeElement.getAttribute('contenteditable') === 'true'
      )) {
        return;
      }

      // 只在多页情况下启用键盘翻页
      if (total <= pagination.pageSize) {
        return;
      }

      // 左右箭头键翻页
      if (event.key === 'ArrowLeft') {
        event.preventDefault();
        handleKeyboardPagination('prev');
      } else if (event.key === 'ArrowRight') {
        event.preventDefault();
        handleKeyboardPagination('next');
      }
    };

    // 添加键盘事件监听
    window.addEventListener('keydown', handleKeyDown);

    // 清理函数
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyboardPagination, total, pagination.pageSize]);

  // 处理筛选变化
  const handleFilterChange = (key: string, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 将团队ID转换为团队名称的辅助函数
  const getTeamNameFromId = (teamValue: string): string => {
    // 如果不是UUID格式，直接返回（已经是团队名称）
    if (!teamValue || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(teamValue)) {
      return teamValue;
    }

    // 查找对应的团队名称
    const team = teams.find(t => t.id === teamValue);
    return team ? team.name : teamValue;
  };

  // 处理排序点击
  const handleSort = (field: string) => {
    setSortState(prev => {
      if (prev.field === field) {
        // 如果点击同一列，切换排序方向
        return {
          field,
          order: prev.order === 'asc' ? 'desc' : 'asc'
        };
      } else {
        // 如果点击不同列，设置为降序
        return {
          field,
          order: 'desc'
        };
      }
    });
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 获取排序图标
  const getSortIcon = (field: string) => {
    if (sortState.field !== field) {
      return <SwapOutlined style={{ color: '#ccc' }} />;
    }
    return sortState.order === 'asc'
      ? <SortAscendingOutlined style={{ color: '#1890ff' }} />
      : <SortDescendingOutlined style={{ color: '#1890ff' }} />;
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setFilters(prev => ({ ...prev, search: value }));
    setPagination(prev => ({ ...prev, current: 1 }));
  };


  // 查看目录下的点位详情
  const handleViewMetrics = (directory: DirectoryInfo) => {
    if (directory.id) {
      // 使用新的directory_id参数
      navigate(`/analysis/points?directory_id=${directory.id}`);
    } else {
      // 回退到旧的路径参数（向后兼容）
      navigate(`/analysis/points?directory=${encodeURIComponent(directory.directory_path)}`);
    }
  };

  // 批量操作处理函数
  const handleBatchUpdateTeam = (directory: DirectoryInfo) => {
    setSelectedDirectory(directory);
    setBatchModalType('team');
    setBatchModalVisible(true);
    setSelectedTeam('');
    setTeamAnalysisNotes('');
  };

  const handleBatchAnalyze = (directory: DirectoryInfo) => {
    setSelectedDirectory(directory);
    setBatchModalType('analysis');
    setBatchModalVisible(true);
    // 重置分析相关状态
    setAnalysisShouldCollect(null);
    setAnalysisReason('');
  };

  const handleBatchConfirm = async () => {
    if (!selectedDirectory) {
      message.error('未选择目录');
      return;
    }

    try {
      setBatchOperationLoading(true);

      if (batchModalType === 'team') {
        if (!selectedTeam) {
          message.warning('请选择目标团队');
          return;
        }

        console.log(`🏢 [DirectoryList] 批量更新遥测点团队`);
        console.log(`   目录: ${selectedDirectory.directory_path}`);
        console.log(`   团队: ${selectedTeam}`);
        console.log(`   分析备注: ${teamAnalysisNotes}`);

        // 调用API批量更新遥测点团队，包含分析内容
        const response = await directoryApi.batchUpdateMetricsTeam({
          directory_path: selectedDirectory.directory_path,
          team_name: selectedTeam,
          analysis_notes: teamAnalysisNotes.trim(),
        });

        if (response.success) {
          message.success(response.message || `已将 ${selectedDirectory.directory_path} 目录下的遥测点分配给团队: ${selectedTeam}`);
        } else {
          message.error('批量更新遥测点团队失败');
          return;
        }
      } else if (batchModalType === 'analysis') {
        // 验证分析参数
        if (analysisShouldCollect === null) {
          message.warning('请选择是否需要采集');
          return;
        }
        if (!analysisReason.trim()) {
          message.warning('请输入分析原因');
          return;
        }

        console.log(`🔍 [DirectoryList] 批量分析遥测点`);
        console.log(`   目录: ${selectedDirectory.directory_path}`);
        console.log(`   需要采集: ${analysisShouldCollect ? '是' : '否'}`);
        console.log(`   分析原因: ${analysisReason}`);

        // 调用API批量分析遥测点
        const response = await directoryApi.batchAnalyzeMetrics({
          directory_path: selectedDirectory.directory_path,
          should_collect: analysisShouldCollect,
          analysis_reason: analysisReason.trim(),
        });

        if (response.success) {
          message.success(response.message || `已启动对 ${selectedDirectory.directory_path} 目录下遥测点的批量分析`);
        } else {
          message.error('批量分析遥测点失败');
          return;
        }
      }

      setBatchModalVisible(false);
      setSelectedDirectory(null);
      setSelectedTeam('');
      setTeamAnalysisNotes('');
      // 重置分析相关状态
      setAnalysisShouldCollect(null);
      setAnalysisReason('');

      // 重新加载数据
      await loadDirectoryList();
    } catch (error) {
      console.error('❌ [DirectoryList] 批量操作失败:', error);
      message.error('批量操作失败');
    } finally {
      setBatchOperationLoading(false);
    }
  };

  const handleBatchCancel = () => {
    setBatchModalVisible(false);
    setSelectedDirectory(null);
    setSelectedTeam('');
    setTeamAnalysisNotes('');
    // 重置分析相关状态
    setAnalysisShouldCollect(null);
    setAnalysisReason('');
  };

  // 表格列定义
  const columns: ColumnsType<DirectoryInfo> = [
    {
      title: (
        <Space style={{ cursor: 'pointer' }} onClick={() => handleSort('name')}>
          <Text>目录路径</Text>
          {getSortIcon('name')}
        </Space>
      ),
      dataIndex: 'directory_path',
      key: 'directory_path',
      width: 300,
      render: (text: string, record: DirectoryInfo) => (
        <Space direction="vertical" size="small">
          <Space>
            <FolderOutlined style={{ color: '#faad14' }} />
            <Text style={{ fontWeight: 500, cursor: 'pointer', color: '#1890ff' }} onClick={() => handleViewMetrics(record)}>
              {text}
            </Text>
          </Space>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {record.file_name}
          </Text>
        </Space>
      ),
    },
    {
      title: (
        <Space style={{ cursor: 'pointer' }} onClick={() => handleSort('metric_count')}>
          <Text>点位统计</Text>
          {getSortIcon('metric_count')}
        </Space>
      ),
      key: 'metrics',
      width: 200,
      render: (_: any, record: DirectoryInfo) => (
        <Space direction="vertical" size="small">
          <Statistic
            title="总点位"
            value={record.metric_count}
            valueStyle={{ fontSize: '16px' }}
            prefix={<BarChartOutlined />}
          />
        </Space>
      ),
    },
    {
      title: (
        <Space style={{ cursor: 'pointer' }} onClick={() => handleSort('analysis_progress')}>
          <Text>分析进度</Text>
          {getSortIcon('analysis_progress')}
        </Space>
      ),
      dataIndex: 'analysis_progress',
      key: 'analysis_progress',
      width: 200,
      render: (progress: number, record: DirectoryInfo) => (
        <Space direction="vertical" size="small">
          <Progress
            percent={progress}
            size="small"
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#52c41a',
            }}
            format={(percent) => `${percent}%`}
          />
          <Space size="small">
            <Text type="success">已分析: {record.analyzed_count}</Text>
            <Text type="warning">待分析: {record.not_analyzed_count}</Text>
          </Space>
        </Space>
      ),
    },
    {
      title: (
        <Space style={{ cursor: 'pointer' }} onClick={() => handleSort('team_name')}>
          <Text>责任团队</Text>
          {getSortIcon('team_name')}
        </Space>
      ),
      key: 'team_info',
      width: 250,
      render: (_: any, record: DirectoryInfo) => (
        <Space direction="vertical" size="small">
          {record.team_name ? (
            <>
              <Space>
                <TeamOutlined style={{ color: '#1890ff' }} />
                <Text strong>{record.team_name}</Text>
              </Space>

              {record.id && (
                <Button
                  type="link"
                  size="small"
                  icon={<UnorderedListOutlined />}
                  onClick={() => {
                    if (record.id) {
                      setSelectedDirectoryForTeam({ id: record.id, path: record.directory_path });
                      setTeamDistributionVisible(true);
                    }
                  }}
                  style={{ padding: '0 4px', height: '20px', fontSize: '11px' }}
                >
                  团队分布 ({record.team_count || 0})
                </Button>
              )}
            </>
          ) : (
            <>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                未分配
              </Text>
              {record.id && (
                <Button
                  type="link"
                  size="small"
                  icon={<UnorderedListOutlined />}
                  onClick={() => {
                    if (record.id) {
                      setSelectedDirectoryForTeam({ id: record.id, path: record.directory_path });
                      setTeamDistributionVisible(true);
                    }
                  }}
                  style={{ padding: '0 4px', height: '20px', fontSize: '11px' }}
                >
                  团队分布 ({record.team_count || 0})
                </Button>
              )}
            </>
          )}
        </Space>
      ),
    },
    {
      title: '批量操作',
      key: 'batch_operations',
      width: 120,
      render: (_: any, record: DirectoryInfo) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleBatchUpdateTeam(record)}
            title="修改遥测点团队"
          />
          <Button
            type="link"
            size="small"
            icon={<PlayCircleOutlined />}
            onClick={() => handleBatchAnalyze(record)}
            title="批量分析遥测点"
          />
        </Space>
      ),
    },
  ];

  // 监听分页和筛选变化
  useEffect(() => {
    console.log('🔄 [DirectoryList] 分页或筛选变化，重新加载目录列表');
    loadDirectoryList();
  }, [pagination.current, pagination.pageSize, filters.search, filters.teamFilter, sortState.field, sortState.order, loadDirectoryList]);

  // 加载总遥测点数量和团队列表（组件加载时执行一次）
  useEffect(() => {
    console.log('🔄 [DirectoryList] 组件加载，获取总遥测点数量和团队列表');
    loadTotalMetrics();
    loadTeams();
  }, []); // 空依赖数组，只在挂载时执行一次

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Content style={{ padding: '24px', background: '#f5f5f5' }}>
        {/* 页面标题和面包屑 */}
        <Card style={{ marginBottom: '16px' }}>
          <Row align="middle" justify="space-between">
            <Col>
              <Space direction="vertical">
                <Title level={3} style={{ margin: 0 }}>
                  目录列表
                </Title>
                <Text type="secondary">
                  查看包含遥测点XML文件的目录及其统计信息
                </Text>
              </Space>
            </Col>
            <Col>
              <Button
                icon={<ReloadOutlined />}
                onClick={loadDirectoryList}
                loading={loading}
              >
                刷新
              </Button>
            </Col>
          </Row>
        </Card>

        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="目录总数"
                value={total}
                prefix={<FolderOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总遥测点"
                value={totalMetrics}
                prefix={<BarChartOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已分析"
                value={directories.reduce((sum, dir) => sum + dir.analyzed_count, 0)}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="平均进度"
                value={directories.length > 0
                  ? Math.round(directories.reduce((sum, dir) => sum + dir.analysis_progress, 0) / directories.length)
                  : 0}
                suffix="%"
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 筛选器 */}
        <Card style={{ marginBottom: '16px' }}>
          <Row gutter={16} align="middle">
            <Col>
              <Input.Search
                placeholder="搜索目录路径..."
                allowClear
                style={{ width: 300 }}
                onSearch={handleSearch}
                onChange={(e) => !e.target.value && handleSearch('')}
              />
            </Col>
            <Col>
              <Select
                placeholder="责任团队"
                value={filters.teamFilter}
                onChange={(value) => handleFilterChange('teamFilter', value)}
                style={{ width: 200 }}
                loading={teamsLoading}
                showSearch
                filterOption={(input, option) =>
                  String(option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
              >
                <Option value="all">所有团队</Option>
                <Option value="unassigned">未分配</Option>
                {teams.map((team) => (
                  <Option key={team.id} value={team.name}>
                    {team.name}
                  </Option>
                ))}
              </Select>
            </Col>
          </Row>
        </Card>

        {/* 目录列表表格 */}
        <Card title="目录列表">
          {/* 键盘快捷键提示 */}
          {total > pagination.pageSize && (
            <div style={{
              marginBottom: '16px',
              padding: '12px',
              background: '#f0f7ff',
              borderRadius: '6px',
              textAlign: 'center',
              fontSize: '12px',
              color: '#666',
              border: '1px solid #d6e4ff'
            }}>
              <Space>
                <Text type="secondary" style={{ fontWeight: 500 }}>键盘快捷键:</Text>
                <Space size="small">
                  <LeftOutlined style={{ fontSize: '12px', color: '#1890ff' }} />
                  <Text keyboard style={{ fontSize: '12px', color: '#1890ff' }}>←</Text>
                  <Text type="secondary">上一页</Text>
                </Space>
                <Text type="secondary">|</Text>
                <Space size="small">
                  <Text keyboard style={{ fontSize: '12px', color: '#1890ff' }}>→</Text>
                  <RightOutlined style={{ fontSize: '12px', color: '#1890ff' }} />
                  <Text type="secondary">下一页</Text>
                </Space>
              </Space>
            </div>
          )}

          <Table
            columns={columns}
            dataSource={directories}
            rowKey={(record) => `${record.directory_path}_${record.file_name}`}
            loading={loading}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
              onChange: handlePaginationChange,
              onShowSizeChange: handlePaginationChange,
            }}
            scroll={{ x: 1000 }}
          />
        </Card>

        {/* 批量操作模态框 */}
        <Modal
          title={batchModalType === 'team' ? '修改遥测点团队' : '批量分析遥测点'}
          open={batchModalVisible}
          onOk={handleBatchConfirm}
          onCancel={handleBatchCancel}
          okText="确认"
          cancelText="取消"
          width={600}
          confirmLoading={batchOperationLoading}
        >
          {selectedDirectory && (
            <>
              <p>
                <strong>目录：</strong>{selectedDirectory.directory_path}
              </p>
              <p>
                <strong>遥测点数量：</strong>{selectedDirectory.metric_count} 个
              </p>
              {batchModalType === 'team' ? (
                <div style={{ marginTop: 16 }}>
                  <div style={{ marginBottom: 16 }}>
                    <p style={{ marginBottom: 8, fontWeight: 500 }}>
                      <strong>1. 选择目标团队：</strong>
                    </p>
                    <Select
                      style={{ width: '100%' }}
                      placeholder="请选择团队"
                      value={selectedTeam}
                      onChange={setSelectedTeam}
                      showSearch
                      filterOption={(input, option) =>
                        String(option?.children || '').toLowerCase().includes(input.toLowerCase())
                      }
                    >
                      <Option value="">-- 请选择团队 --</Option>
                      {teams.map((team) => (
                        <Option key={team.id} value={team.name}>
                          {team.name}
                        </Option>
                      ))}
                    </Select>
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <p style={{ marginBottom: 8, fontWeight: 500 }}>
                      <strong>2. 分析备注（可选）：</strong>
                    </p>
                    <Input.TextArea
                      value={teamAnalysisNotes}
                      onChange={(e) => setTeamAnalysisNotes(e.target.value)}
                      placeholder="请输入团队分配的分析原因或备注..."
                      rows={3}
                      maxLength={500}
                      showCount
                    />
                  </div>

                  <div style={{ marginTop: 16, padding: 12, backgroundColor: '#f6f6f6', borderRadius: 6 }}>
                    <p style={{ color: '#faad14', margin: 0 }}>
                      <strong>说明：</strong>
                    </p>
                    <ul style={{ color: '#666', marginLeft: 20, marginBottom: 0, marginTop: 8 }}>
                      <li>团队分配将应用到该目录下的所有 {selectedDirectory.metric_count} 个遥测点</li>
                      <li>系统将在 metrics 表中更新遥测点的归属团队</li>
                      <li>系统将在 telemetry_analysis 表中为每个遥测点增加新的分析记录</li>
                      <li>分析备注不会影响遥测点的分析状态，仅作为记录参考</li>
                    </ul>
                  </div>
                </div>
              ) : (
                <div style={{ marginTop: 16 }}>
                  <div style={{ marginBottom: 16 }}>
                    <p style={{ marginBottom: 8, fontWeight: 500 }}>
                      <strong>1. 是否需要采集：</strong>
                    </p>
                    <Radio.Group
                      value={analysisShouldCollect}
                      onChange={(e) => setAnalysisShouldCollect(e.target.value)}
                      style={{ width: '100%' }}
                    >
                      <Radio value={true} style={{ display: 'block', marginBottom: 8 }}>
                        需要采集
                      </Radio>
                      <Radio value={false} style={{ display: 'block' }}>
                        不需要采集
                      </Radio>
                    </Radio.Group>
                  </div>

                  <div style={{ marginBottom: 16 }}>
                    <p style={{ marginBottom: 8, fontWeight: 500 }}>
                      <strong>2. 分析原因：</strong>
                    </p>
                    <Input.TextArea
                      value={analysisReason}
                      onChange={(e) => setAnalysisReason(e.target.value)}
                      placeholder="请输入分析原因..."
                      rows={3}
                      maxLength={500}
                      showCount
                    />
                  </div>

                  <div style={{ marginTop: 16, padding: 12, backgroundColor: '#f6f6f6', borderRadius: 6 }}>
                    <p style={{ color: '#faad14', margin: 0 }}>
                      <strong>注意：</strong>
                    </p>
                    <ul style={{ color: '#666', marginLeft: 20, marginBottom: 0, marginTop: 8 }}>
                      <li>批量分析将处理该目录下的所有 {selectedDirectory.metric_count} 个遥测点</li>
                      <li>上述设置将应用到该目录下的所有遥测点</li>
                      <li>分析过程可能需要较长时间，请耐心等待</li>
                    </ul>
                  </div>
                </div>
              )}
            </>
          )}
        </Modal>

      {/* 团队分布 ({record.team_count || 0})弹窗 */}
      <TeamDistributionModal
        visible={teamDistributionVisible}
        onClose={() => {
          setTeamDistributionVisible(false);
          setSelectedDirectoryForTeam(null);
        }}
        directoryId={selectedDirectoryForTeam?.id || 0}
        directoryPath={selectedDirectoryForTeam?.path || ''}
      />
      </Content>
    </Layout>
  );
};

export default DirectoryList;